package com.hmjk.health.home;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.NetService;
import com.hmjk.health.util.OnFragmentEventCallback;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.InputType;
import android.text.format.Time;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.NumberKeyListener;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class SignInFragment extends Fragment implements OnClickListener, OnTouchListener{
	private final String TAG = SignInFragment.class.getSimpleName(); 
	private HealthApp mApp = null;
	private OnFragmentEventCallback mCallback;
	private EditText mUsername;
	private EditText mPassword;
	private Button mSignIn;
	private TextView mErrHint;
	private String suser;
	private String spwd;
	private String remUser;
	private boolean attached = false;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onAttach(Activity activity){
		super.onAttach(activity);
		mApp = (HealthApp)activity.getApplication();
		try{
			mCallback = (OnFragmentEventCallback)activity;
		}catch(ClassCastException e){
			throw new ClassCastException(activity.getClass().getName() + " must implement OnFragmentEventCallback");
		}
		attached = true;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
		logd("onCreateView");
		View v = inflater.inflate(R.layout.signin_fragment, container, false);
		
		TextView signUp = (TextView)v.findViewById(R.id.signup);
		String ssignup = getResources().getString(R.string.signup);
		signUp.setText(Html.fromHtml(ssignup));
		
		signUp.setOnClickListener(this);
		
		TextView regetPsw = (TextView)v.findViewById(R.id.retrievepwd);
		String regetpsw = getResources().getString(R.string.regetpsw);
		regetPsw.setText(Html.fromHtml(regetpsw));
		
		regetPsw.setOnClickListener(this);	
		
		ImageButton back = (ImageButton)v.findViewById(R.id.back);
		back.setOnClickListener(this);
		remUser = mApp.getUserName();
		mUsername = (EditText)v.findViewById(R.id.useredit);
	//	mUsername.addTextChangedListener(this);
		mUsername.setKeyListener(new NumberKeyListener(){

			@Override
			public int getInputType() {
				return InputType.TYPE_CLASS_TEXT;
			}

			@Override
			protected char[] getAcceptedChars() {
				char[] allow = mApp.getAllowedChars("UserName");
				return allow;
			}
			
		});
		mPassword = (EditText)v.findViewById(R.id.pwdedit);
		mPassword.setKeyListener(new NumberKeyListener(){

			@Override
			public int getInputType() {
				return InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD;
			}

			@Override
			protected char[] getAcceptedChars() {
				char[] allow = mApp.getAllowedChars("Password");
				return allow;
			}
			
		});
		mSignIn = (Button)v.findViewById(R.id.signin_but);
		mSignIn.setOnClickListener(this);
		
		mErrHint = (TextView)v.findViewById(R.id.err_hint);
		
		ImageButton see = (ImageButton)v.findViewById(R.id.see);
		see.setOnTouchListener(this);
		attached = true;
		updateView(false,false,null);
		return v;
	}
	
	public void updateUser(String user){
		logd("upateUser");
		remUser = user;
	}
	
	@Override
	public void onResume(){
		super.onResume();
		logd("onResume");
		if((mUsername != null) && (remUser != null)){
			mUsername.setText(remUser);
			mUsername.setSelection(remUser.length());
		}
	}
	
	@Override
	public void onDetach(){
		attached = false;
		super.onDetach();
		logd("onDetach");
	}
	
	@Override
	public void onDestroyView(){
		attached = false;
		super.onDestroyView();
		logd("onDestroyView");
	}
	
	
	private boolean checkInput(){
		boolean userok = true;
		boolean pwdok = true;
		String errhint = null;
		suser = mUsername.getText().toString().trim();
		if((suser == null) || suser.isEmpty())
			userok = false;
		
		if(userok){
			spwd = mPassword.getText().toString().trim(); 
			if((spwd == null) || spwd.isEmpty())
				pwdok = false;
			else if(spwd.length() < 6){
				pwdok = false;
				errhint = getActivity().getResources().getString(R.string.pwd_err);
			}else{
				String pwdErr = mApp.validPassword(spwd); 
				if(pwdErr != null){
					pwdok = false;
					errhint = getActivity().getResources().getString(R.string.pwd_err_with, pwdErr);
				}
			}
		}
		
		updateView(userok, pwdok, errhint);
		return (userok && pwdok);
	}
	
	private void updateView(boolean isUserOk, boolean isPwdOk, String ErrStr){
		if(isUserOk && isPwdOk){
			//mSignIn.setEnabled(true);
			mErrHint.setVisibility(View.INVISIBLE);
		}else{
			//mSignIn.setEnabled(false);
			if(ErrStr != null){
				mErrHint.setText(ErrStr);
				mErrHint.setVisibility(View.VISIBLE);
			}else{
				mErrHint.setVisibility(View.INVISIBLE);
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.signin_but:{
			if(checkInput()){
				//TODO:sign in
				logd("sign in:"+suser + ":"+spwd);
				mApp.showWaitting(getActivity(), null);
				Intent si = new Intent(getActivity(), NetService.class);
				si.setAction(NetService.SIGN_IN_ACCOUNT);
				si.putExtra("user", suser);
				si.putExtra("password", spwd);
				Time t = new Time();
				t.setToNow();
				String stamp = "SIGN_IN_ACCOUNT" + t.toString(); 
				si.putExtra("stamp",stamp);
				mApp.addNetHandler(stamp,mHandler);
				getActivity().startService(si);
			}
		}
		break;
		case R.id.signup:{
			mCallback.onEvent(SignInActivity.ACT_SWITCH_TO_SIGNUP, null);
		}
		break;
		case R.id.retrievepwd:{
			mCallback.onEvent(SignInActivity.ACT_SWITCH_TO_RETRIEVEPSW, null);
		}
		break;
		case R.id.back:{
			getActivity().finish();
		}
		break;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent e) {
		if(v.getId() == R.id.see){
			
			if(e.getAction() == MotionEvent.ACTION_DOWN){
				//see pwd
				int pos = mPassword.getSelectionStart();
				mPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
				mPassword.setSelection(pos);
			}else if((e.getAction() == MotionEvent.ACTION_UP) ||
					(e.getAction() == MotionEvent.ACTION_CANCEL)){
				//hide pwd
				int pos = mPassword.getSelectionStart();
				mPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
				mPassword.setSelection(pos);
			}
		}
		return false;
	}

	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			if(!attached)
				return;
			
			switch(msg.what){
			case HealthApp.MSG_NET_RESPONSE:{
				Bundle b = msg.getData();
				String stamp = b.getString("stamp","ooh!No!");
				boolean canceled = b.getBoolean("canceled", false);
				if(stamp.startsWith("SIGN_IN_ACCOUNT")){
					mApp.dismissWaiting();
					if(mApp.isSignIn()){
						getActivity().setResult(Activity.RESULT_OK);
						getActivity().finish();
					}
				}
			}
			break;
			}
		}
	};
}
